I tried Remote State And State Locking in Terraform Using S3
Why is the tfstate file necessary?
- One advantage of the terraformed state is the ability for TerraForm to build and delete resources in the proper sequence by tracking dependencies and mapping Terraform configuration to real-world infrastructure.
-
enhancing TerraForm operations performance while working with big configuration files, particularly those that employ several cloud providers.
-
The TerraForm state enables team members to communicate and provide resources together.
What is a Remote State?
With a remote state, Terraform writes the state data to a remote data store, which can be shared between all team members.
Terraform Remote State Storage Options
Terraform supports storing state in
- Amazon S3
- Azure Blob Storage
- Google Cloud Storage
- Terraform Cloud
- HashiCorp Consul
- Many more.
Pre-requisite:
1.S3 bucket, which will be used to store data from the state file. 2. Dynamo DB table, which will be used to implement state locking and consistency checks. Use this terraform for creating the same
provider "aws" { region = "ap-northeast-1" shared_credentials_file = "~/.aws/credentials" } resource "aws_s3_bucket" "tf_course" { bucket = "deviostatefile" acl = "private" } resource "aws_dynamodb_table" "dynamodb-terraform-state-lock" { name = "terraform-state-lock-dynamo" hash_key = "LockID" read_capacity = 20 write_capacity = 20 attribute { name = "LockID" type = "S" } }
Note: A. bucket name, B. the key to be used, C. the region D.the name of the DynamoDb Table
Remote state setup can be achieved by setting up backends specific to the cloud.
Setting up a remote state in Amazon S3:
backend.tf
terraform { backend "s3" { bucket = "deviostatefile" dynamodb_table = "terraform-state-lock-dynamo" key = "prod_terraform.tfstate" region = "ap-northeast-1" } }
After terraform Apply:
- we can verify the state file stored in remote location [Amazon s3]
Conclusion :
This hands on will help teams to collaborate more efficiently. Developers and engineers will work without worrying about loosing and corrupting there tfstate file hope this blog helps
Reference :
https://dev.classmethod.jp/articles/integrate-terraform-remote-state-hub/ https://www.terraform.io/language/state/remote-state-data